package com.cssl.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

@org.springframework.stereotype.Controller
public class UploadController implements ServletContextAware {
	
	public ServletContext application;
	
	@Override
	public void setServletContext(ServletContext arg0) {
		this.application=arg0;
		
	}
	/**
	 * 上传
	 * @param files
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("/upload")
	public String upload(MultipartFile[] files) throws Exception {
		System.out.println("上传....");
		String path = application.getRealPath("/upload");
		
		for (int i = 0; i < files.length; i++) {
			if(!files[i].isEmpty()) {
				String fileName = UUID.randomUUID()+files[i].getOriginalFilename();
				File df = new File(path,fileName);
				files[i].transferTo(df);
			}
		}
		
		return "ok";
	}
	/**
	 * 上传
	 * @param files
	 * @return
	 * @throws Exception 
	 */
	@GetMapping("/download")
	public void download(String fileName,HttpServletResponse response) throws Exception {
		System.out.println("下载....");
		String path = application.getRealPath("/upload");
		InputStream is=new FileInputStream(path+File.separator+fileName);
		
		response.setContentType("application/x-msdownload;charset=UTF-8");		
		response.setHeader("Content-disposition", "attachment;filename="+fileName);
		OutputStream os = response.getOutputStream();
		
		byte[] b = new byte[4096];
		int len = is.read(b);
		while(len!=-1) {
			os.write(b, 0, len);
			len = is.read(b);
		}
		os.flush();
		os.close();
		is.close();
	}
}
